/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Level } from '../Level';
import socket from '@ohos.net.socket';
import { Appender } from '../config/Appender'

export class SocketAppender {
    private remoteHost: string
    private port: number
    private tcp: socket.TCPSocket;
    private FAMILY = 1
    private OUT_TIME = 6000

    async bind(appender: Appender) {
        this.remoteHost = appender.remoteHost
        this.port = appender.port
        this.tcp = socket.constructTCPSocketInstance();
        await this.tcp.bind({ address: this.remoteHost, port: this.port, family: this.FAMILY });
        await this.tcp.connect({
            address: { address: this.remoteHost, port: this.port, family: this.FAMILY },
            timeout: this.OUT_TIME
        });
    }

    start(level: Level, msg: string) {
        this.tcp.send({
            data: `${level} ${msg}`
        }).then(() => {
            console.info('send success');
        }).catch(err => {
            console.error('send fail' + JSON.stringify(err));
        })
    }
}